<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user.js'
const { user: {username, nickname, id, email}, getUser } = useUserStore()
// 定义数据
const formRef = ref()
// 是在使用仓库中数据的初始值（无需响应式）解构无问题
const formModel = ref({
  id,
  username,
  nickname,
  email
})
// 表单校验
const rules = {
  username: [
    {required: true, message: '请输入登录名称', trigger: 'blur'},
    {pattern: /^\S{2,10}$/, message: '登录名称必须是2-10位的非空字符', trigger: 'blur'}
  ],
  nickname: [
    {required: true, message: '请输入用户昵称', trigger: 'blur'},
    {pattern: /^\S{2,10}$/, message: '用户昵称必须是2-10位的非空字符', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入用户邮箱', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur','change']}
  ]
}

// 点击提交
const onSubmit = async () => {
  console.log('提交修改')
  // 等待校验结果
  await formRef.value.validate()
  // 提交修改
  await userUpdateInfoService(formModel.value)
  // 通知 user 模块，进行数据更新
  getUser()
  // 提示用户
  ElMessage.success('修改成功')
}
</script>

<template>
  <PageContainer title="基本资料">
    <!--表单部分-->
    <el-form ref="formRef" :model="formModel" :rules="rules" label-width="100px">
      <el-form-item label="登录名称" prop="username">
        <el-input v-model="formModel.username" placeholder="请输入登录名称"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formModel.nickname" placeholder="请输入用户昵称"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="formModel.email" placeholder="请输入用户邮箱"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="onSubmit" type="primary">提交修改</el-button>
      </el-form-item>
    </el-form>
  </PageContainer>
</template>

<style>

</style>
